///<reference path="../lib/pixi.js.d.ts"/>

class Button
{
    name: string;
    container: PIXI.Container;
    text: PIXI.Text;
    sprite: PIXI.mesh.NineSlicePlane;
    callback: Function;
    private defPosition: PIXI.Point;
    private defColor: number;
    private pressed = false;
    constructor (label: string = "Button", btnWidth: number = 128, btnHeight: number = 64, imageUrl: string = "../res/uisprite.png")
    {
        this.name = label;

        this.container = new PIXI.Container();
        this.defPosition = new PIXI.Point(this.container.position.x, this.container.position.y);

        let texture = PIXI.Texture.fromImage(imageUrl);
        this.sprite = new PIXI.mesh.NineSlicePlane(texture, 16, 16, 16, 16);
        this.btnWidth = btnWidth;
        this.btnHeight = btnHeight;
        this.sprite.tint = 0xffffff;
        this.sprite.buttonMode = true;
        this.sprite.interactive = true;
        this.sprite.on("mousedown", (e) => { this.onDown(); });
        this.sprite.on("touchstart", (e) => { this.onDown(); });
        this.sprite.on("click", (e) => { this.onClick(); });
        this.sprite.on("tap", (e) => { this.onClick(); });
        this.container.addChild(this.sprite);

        this.text = new PIXI.Text(label);
        this.text.anchor.set(0.5, 0.5);
        this.text.style.fontSize = 24;
        this.container.addChild(this.text);

        document.addEventListener("mouseup", (e) => { this.onUp(); });
        document.addEventListener("touchend", (e) => { this.onUp(); });
    }

    private onDown()
    {
        this.defPosition.x = this.container.position.x;
        this.defPosition.y = this.container.position.y;
        this.defColor = this.sprite.tint;

        this.sprite.tint = (this.sprite.tint & 0xeeeeee) >> 1;
        this.container.position.x += 2;
        this.container.position.y += 2;

        this.pressed = true;
    }

    private onUp()
    {
        if (this.pressed)
        {
            this.sprite.tint = this.defColor;
            this.container.position.x = this.defPosition.x;
            this.container.position.y = this.defPosition.y;

            this.pressed = false;
        }
    }

    private onClick()
    {
        if (this.callback != null)
        {
            this.callback();
        }
    }

    get btnWidth(): number
    {
        return this.sprite.width;
    }
    set btnWidth(width: number)
    {
        this.sprite.width = width;
        this.sprite.position.x = -(width / 2);
    }

    get btnHeight(): number
    {
        return this.sprite.height;
    }
    set btnHeight(height: number)
    {
        this.sprite.height = height;
        this.sprite.position.y = -(height / 2);
    }
}